
package com.dotools.ui;

import android.util.DisplayMetrics;
import android.view.View;

import com.dotools.cache.LruCache;
import com.dotools.debug.LOG;
import com.dotools.utils.DevicesUtils;
import com.dotools.utils.Utilities;

public class ViewCache extends LruCache<View, ViewCacheEntry> {
    private static ViewCache sInstance = null;

    public static ViewCache getInstance() {
        if (sInstance == null) {
            DisplayMetrics dm = Utilities.getApplicationContext().getResources().getDisplayMetrics();
            final int screenSize = dm.widthPixels * dm.heightPixels * 4;
            final int heapSize = DevicesUtils.getHeapSize() * 1024 * 1024 / 24;
            LOG.logI("setup ViewCache: screenFactor=" + screenSize + ", heapFactor=" + heapSize);
            sInstance = new ViewCache(Math.min(screenSize, heapSize));
        }
        return sInstance;
    }

    private ViewCache(int maxSize) {
        super(maxSize);
    }

    @Override
    protected synchronized void entryRemoved(boolean evicted, View key, ViewCacheEntry oldValue, ViewCacheEntry newValue) {
        oldValue.recycle();
    }

    @Override
    protected synchronized int sizeOf(View key, ViewCacheEntry value) {
        return value.size;
    }
}
